package com.zhang.sql;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.Tumble;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.*;

/**
 * @title:
 * @author: zhang
 * @date: 2022/2/13 21:47
 */
public class GroupWindowTumblingEventTimeTableApi {
    public static void main(String[] args) throws Exception {
        //获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //从端口读取数据，提取时间戳和分配水位线
        SingleOutputStreamOperator<Tuple2<String, Long>> streamOperator = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> map(String value) throws Exception {
                        String[] fields = value.split(" ");
                        return Tuple2.of(
                                fields[0],
                                Long.parseLong(fields[1]) * 1000L
                        );
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple2<String, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                                    @Override
                                    public long extractTimestamp(Tuple2<String, Long> element, long recordTimestamp) {
                                        return element.f1;
                                    }
                                })
                );

        //table API 开窗
        Table table = tableEnv.fromDataStream(streamOperator,
                $("word"),
                $("count"),
                $("rt").rowtime());

        Table result = table.window(Tumble.over(lit(5).second()).on($("rt")).as("w"))
                .groupBy($("word"), $("w"))
                .select($("word"),$("word").count());

        tableEnv.toAppendStream(result, Row.class).print();

        env.execute();
    }
}
